#include <stdio.h>
#include <stdlib.h>
#include "disks.h"
#include "consts.h"
#include "device.h"
#include "syscall.h"
#include "function.h"

public dev device_list[N_DEV];

tword get_device_size(int dev_no)
{
    return device_list[dev_no].device_size;
}

int read_blocks(int dev_no, dword block_begin, int count, void* buffer_in)
{
    dev* d= &device_list[dev_no];
    FILE* fp;
    
    if ( d->device_type != block_device)
        return panic("Wrong Device: no block device");
        
    if ( block_begin + count > d->device_size )
    	return -1;

    if ( (fp = fopen( d->dev_description, "r")) == NULL )
        return panic("device open error. can't open block device");
    
    if ( fseek(fp, BLOCK_SIZE * block_begin, SEEK_SET)== -1 ) return -1;
    if ( fread(buffer_in, sizeof(byte), BLOCK_SIZE * count, fp) < BLOCK_SIZE * count )
        return panic("read device error.");
    
    fclose(fp);

    return 1;
}

int write_blocks(int dev_no, dword block_begin, int count, void* buffer_out)
{
    dev* d=&device_list[dev_no];
    FILE* fp;

    if ( d->device_type != block_device )
        return -1;

    if ( block_begin + count > d->device_size )
    	return -1;

    fp = fopen( d->dev_description, "r+b");

    if ( fp==NULL )
        return panic("open file error.");
    
    if ( fseek(fp, BLOCK_SIZE * block_begin, SEEK_SET)!=0 )
        return panic("write error.");
    if ( fwrite(buffer_out, sizeof(byte), BLOCK_SIZE * count, fp)!=BLOCK_SIZE * count )
        return panic("write error.");

    fclose(fp);
    return 1;
}

int read_block(int dev_no, dword block_no, void *buffer_in)
{
	return read_blocks(dev_no, block_no, 1, buffer_in);
}

int write_block(int dev_no, dword block_no, void *buffer_out)
{
	return write_blocks(dev_no, block_no, 1, buffer_out);
}

